/**
 * 通用网络请求
 * 基于 Promise 响应拦截
 */
import store from '@/store/index'
export let BASE_URL
export let SOCKET_URL
// #ifdef H5
BASE_URL = '//app.huaxia-health.com/' // 生产
SOCKET_URL = ''
// #endif
//正式服务器
// #ifndef H5
BASE_URL = 'http://app.huaxia-health.com/' // 生产
SOCKET_URL = ''// 生产
// #endif

// 版本号以及运行平台
let version = '1.0.0'
let appType = '3'
// #ifdef APP-PLUS
// 手机品牌
plus.runtime.getProperty(plus.runtime.appid, wgtinfo => {
  version = wgtinfo.version
});
// #endif
// #ifdef MP-WEIXIN
version = wx.getAccountInfoSync().miniProgram.version
//#endif

export default {
  config: {
    showToast:true,
    baseUrl: BASE_URL,
    baseSocketUrl: SOCKET_URL,
    header: {
      "Content-Type": "application/json;charset=UTF-8",
      appType: appType,
      version: version,
      // #ifdef APP-PLUS
      versioncode: plus.runtime.versionCode,
      // #endif
      sn: '',
      KaToken: ''
    },
    data: {
    },
    method: "GET",
    dataType: "json",
    responseType: "text",
    success() {},
    fail() {},
    complete() {}
  },
  interceptor: {
    request: null,
    response: null
  },
  request(options) {
    if (!options) {
      options = {};
    }
    this.config.header.version = version
    this.config.header.KaToken = uni.getStorageSync('KaToken') || ''
    
    options.showToast=typeof options.showToast == 'boolean'?options.showToast:this.config.showToast
    options.baseUrl = options.baseUrl || this.config.baseUrl;
    options.dataType = options.dataType || this.config.dataType;
    options.method = options.method || this.config.method;
    
    options.header = Object.assign({}, options.header, this.config.header);
    options.data = Object.assign({}, this.config.data, options.data);
    options.url = options.url;
    //TODO 加密数据（预留）

    //TODO 数据签名
    try {
      
    } catch (e) {
      // error
    }
    return new Promise((resolve, reject) => {
      let _config = null;
      options.complete = response => {
        // uni.hideToast();
        let statusCode = String(response.statusCode);
        response.config = _config;
        if (process.env.NODE_ENV === "development") {
          if (statusCode === '200') {
            // console.log(
            //     "【" +
            //         _config.requestId +
            //         "】 结果：" +
            //         JSON.stringify(response.data)
            // );
          }
        }
        if (this.interceptor.response) {
          let newResponse = this.interceptor.response(response);
          if (newResponse) {
            response = newResponse;
          }
        }
        // 统一的响应日志记录
        _reslog(response);
        if (statusCode === '200' && response.data) {
          // console.log(options.url);
          // console.log('response.data',response.data);
          //成功
          
          let res = response.data
          if (res.status == 200) {
            resolve(res);
          } else {
            uni.stopPullDownRefresh();
            if (res.status == 101) {
              store.dispatch('resetStore')
              uni.$app.logout()
              uni.hideLoading()
              uni.reLaunch({
                url: '/pages/login/main'
              })
              // uni.$navigateTo("/pages/auth/mobile")
              reject(response);
            } else if (res.status == 102) {
              this.request({
                url: this.config.baseUrl + 'api/v1/refresh.token',
                method: 'post',
              }).then(ress => {
                if (ress?.data?.token) {
                  let KaToken = ress.data.token
                  uni.setStorageSync('KaToken', KaToken)
                  this.config.header.KaToken = KaToken
                  this.request(options).then(e => {
                    if (e.status == 200) {
                      resolve(e);
                    }
                  })
                }
              })
            } else {
              if(options.showToast){
                uni.hideLoading()
                uni.showToast({
                  title: `${res.message || res}`,
                  icon: "none",
                });
              }
              reject(response);
            }
          }
        } else if (statusCode.slice(0, 1) == 3 || statusCode.slice(0, 1) == 4 || statusCode.slice(0, 1) == 5) {
          uni.showToast({
            title: `客官请稍等(${statusCode})`,
            icon: "none",
            // position: "bottom"
          });
          uni.stopPullDownRefresh();
          reject(response);
        } else {
          reject(response);
        }
      };

      _config = Object.assign({}, this.config, options);
      _config.requestId = new Date().getTime();

      if (this.interceptor.request) {
        this.interceptor.request(_config);
      }

      // 统一的请求日志记录
      _reqlog(_config);

      if (process.env.NODE_ENV === "development") {
        // console.log(
        //     "【" + _config.requestId + "】 地址：" + _config.url
        // );
        if (_config.data) {
          // console.log(
          //     "【" +
          //         _config.requestId +
          //         "】 参数：" +
          //         JSON.stringify(_config.data)
          // );
        }
      }

      uni.request(_config);
    });
  },
  get(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = "GET";
    return this.request(options);
  },
  post(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = "POST";
    return this.request(options);
  },
  put(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = "PUT";
    return this.request(options);
  },
  delete(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = "DELETE";
    return this.request(options);
  },
  upload(url, filePath, name) {
    return new Promise(function(resolve, reject) {
      let token = uni.getStorageSync('token')
      uni.uploadFile({
        url,
        filePath,
        name,
        header: {
          'X-Mall-Token': token
        },
        success: function(res) {
          if (res.statusCode == 200) {
            if (res.data.errno == 501) {
              // 清除登录相关内容
              try {
                uni.removeStorageSync('userInfo');
                uni.removeStorageSync('token');
                // 切换到登录页面
                uni.redirectTo({
                  url: '/pages/k-login/index'
                });
              } catch (e) {
                // Do something when catch error
              }
            } else {
              try {
                resolve(JSON.parse(res.data));
              } catch (error) {
                uni.showToast({
                  title: '图片太大，无法上传',
                  icon: 'none'
                })
              }
            }
          } else {
            reject(res.errMsg);
          }
        },
        fail: function(err) {
          reject(err)
        }
      })
    });
  }
};

/**
 * 请求接口日志记录
 */
function _reqlog(req) {
  if (process.env.NODE_ENV === "development") {
    // console.log("【" + req.requestId + "】 地址：" + req.url);
    if (req.data) {
      // console.log(
      //     "【" +
      //         req.requestId +
      //         "】 请求参数：" +
      //         JSON.stringify(req.data)
      // );
    }
  }
  //TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
  let _statusCode = "";
  if (res.statusCode) {
    _statusCode = res.data.errCode;
  }
  if (process.env.NODE_ENV === "development") {
    // console.log("【" + res.config.requestId + "】 地址：" + res.config.url);
    if (res.config.data) {
      // console.log(
      //     "【" +
      //         res.config.requestId +
      //         "】 请求参数：" +
      //         JSON.stringify(res.config.data)
      // );
    }
    // console.log(
    //     "【" + res.config.requestId + "】 响应结果：" + JSON.stringify(res)
    // );
  }
  //TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
  switch (_statusCode) {
    case 200:
      break;
    case 501:
      uni.showToast({
        title: "登录过期，请重新登录！",
        icon: "none"
      });
      uni.removeStorage({
        key: 'db_userInfo'
      })
      uni.reLaunch({
        url: "/pages/home/user/login/index"
      })
      return;
    case 404:
      break;
    default:
      break;
  }
}
